#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
//#include <string.h>
#include <assert.h>

namespace cp
{
	class string
	{
	public:
		string(const char* str = "")
		{
			_size = strlen(str);
			_capacity = _size;
			_str = new char[_capacity + 1];

			strcpy(_str, str);
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
			_size = 0;
			_capacity = 0;
		}

		typedef char* iterator;
		typedef char* const_iterator;
		iterator begin()
		{
			return _str;
		}

		const_iterator begin() const
		{
			return _str;
		}

		iterator end()
		{
			return _str + _size;
		}

		const_iterator end() const
		{
			return _str + _size;
		}

		size_t size() const
		{
			return _size;
		}

		const char& operator[](size_t pos) const
		{
			return _str[pos];
		}

		char& operator[](size_t pos) 
		{
			return _str[pos];
		}

		const char* c_str() const
		{
			return _str;
		}

		void reserve(size_t n)
		{
			if (n > _capacity)
			{
				char* tmp = new char[n + 1];
				strcpy(tmp, _str);
				delete[] _str;
				_str = tmp;
				_capacity = n;
			}
		}

		void push_back(const char c)
		{
			if (_size == _capacity)
			{
				size_t newcapacity = _capacity == 0 ? 4 : _capacity * 2;
				reserve(newcapacity);
			}

			_str[_size++] = c;
			_str[_size] = '\0';
		}

		void append(const char* str)
		{
			size_t len = strlen(str);
			if (len + _size > _capacity)
			{
				reserve(_size + len);
			}

			strcpy(_str + _size, str);
			_size += len;
		}


	private:
		char* _str;
		size_t _size;
		size_t _capacity;
	};

	void print_str(const string& s)
	{
		for (int i = 0; i < s.size(); i++)
		{
			cout << s[i] ;
		}
		cout << endl;
	}


	void test_string()
	{
		string s("hello world");
		print_str(s);

		cout << s.c_str() << endl;

		for (auto c : s)
		{
			cout << c << " ";
		}
		cout << endl;

		const string s1("hello world!!!");
		string::const_iterator it = s1.begin();
		while (it != s1.end())
		{
			cout << *it << " ";
			++it;
		}
		cout << endl;

		for (int i = 0; i < s1.size(); i++)
		{
			cout << s1[i] << " ";
		}
		cout << endl;
		print_str(s1);
	}

	void test_string1()
	{
		string s("hello world");
		s.push_back('6');
		print_str(s);

		string s1("66666");
		s1.append("777777");
		print_str(s1);
	}
}


